package com.yty.system.oauth.config.exception;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 无效 token 异常类重写
 */

@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<String, Object>();
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if (Objects.isNull(cause)) {
                R<Object> r = R.failed("认证失败，请传递token");
                response.getWriter().write(JSONObject.toJSONString(r));
                return;
            }
            if(cause instanceof InvalidTokenException) {
                R<Object> r = R.failed("认证失败，token无效或已过期");
                response.getWriter().write(JSONObject.toJSONString(r));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
